package com.ybkj.daijia.api.weixin.v1;

import com.ybkj.daijia.BrandList;
import com.ybkj.daijia.CityList;
import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.WxSetting;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.driver.v3.ProcessController;
import com.ybkj.daijia.common.Distance;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Brand;
import com.ybkj.daijia.server.model.Car.TransmissionCase;
import com.ybkj.daijia.server.model.CarType;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Order.OrderCarType;
import com.ybkj.daijia.server.model.Order.OrderCarTypeDetail;
import com.ybkj.daijia.server.model.Rate;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.service.BrandService;
import com.ybkj.daijia.server.service.CarService;
import com.ybkj.daijia.server.service.CarTypeService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.PhoneSmsRecordService;
import com.ybkj.daijia.server.service.RateService;
import com.ybkj.daijia.server.service.WxBindService;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("m")
public class MController {


    private static final Logger logger = LoggerFactory.getLogger(ProcessController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private RateService rateService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PhoneSmsRecordService phoneSmsRecordService;

    @Autowired
    private WxBindService wxBindService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CarService carService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CarTypeService carTypeService;


    @RequestMapping(value = "loading")
    public ModelAndView myAccount(String openId) {

        ModelAndView mv = new ModelAndView();

        mv.setViewName("m/loading");
        return mv;
    }

    /**
     * 微信客户端客户获取附近司机
     *
     * @param longitude 经度
     * @param latitude  纬度
     * @param type      0代驾 1专车
     * @return
     */
    @RequestMapping(value = "queryNearDrivers", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryNearDrivers(Double longitude, Double latitude) {
        logger.debug("weixin longitude:{},latitude:{}", longitude, latitude);
        if (longitude == null || latitude == null) {
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
            return instance;
        }
        List<Driver> drivers = driverService.wxQueryDriver(longitude, latitude, 0);

        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(drivers)) {
            for (Driver driver : drivers) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("driverId", driver.getId());
                map.put("driverName", driver.getName());
                map.put("driverUserName", driver.getUsername());
                if (driver.getPhoto() != null) {
                    map.put("driverHead", driver.getPhoto());
                } else {
                    map.put("driverHead", null);
                }
                map.put("driverStar", driver.getStarLevel());
                map.put("driverTimes", driver.getDriveTimes());
                map.put("driverJialing", driver.getjialing());
                map.put("driverDistance", driver.getDistanceStr());
                map.put("driverMeter", driver.getDistance() * 1000);
                map.put("driverLng", driver.getLongitude());
                map.put("driverLat", driver.getLatitude());
                mapList.add(map);
            }
        }
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
        instance.setData(mapList);
        return instance;
    }

    @RequestMapping(value = "driverDetails", method = RequestMethod.GET)
    public ModelAndView memberOrder(Long driverId, Double longitude, Double latitude) {
        logger.debug("longitude:{},latitude:{},driverId:{}", longitude, latitude, driverId);

        ModelAndView mv = new ModelAndView();
        Driver driver = driverService.findOne(driverId);

        double distance = Distance
            .doubleVal(latitude, longitude, driver.getLatitude(), driver.getLongitude());
        driver.setDistance(distance);
        DecimalFormat df = new DecimalFormat("#.00");
        if (distance >= 1) {
            driver.setDistanceStr(df.format(distance) + "公里");
        } else {
            driver.setDistanceStr((long) (distance * 1000) + "米");
        }

        mv.addObject("driverName", driver.getDistanceStr());
        mv.addObject("driverDistance", driver.getDistanceStr());
        mv.addObject("driverTimes", driver.getDriveTimes());
        mv.addObject("driverJialing", driver.getjialing());
        mv.addObject("driverLng", driver.getLongitude());
        mv.addObject("driverLat", driver.getLatitude());
        mv.addObject("driverStar", driver.getStarLevel());
        mv.addObject("page", rateService.pageRateByDriver(driverId, 0, 10));
        mv.addObject("total", rateService.queryAll(driverId, null, null).getNumberOfElements());
        mv.addObject("driverId", driverId);
        mv.addObject("setting", settingUtils.getWx());
        mv.addObject("photo", driver.getPhoto());

        mv.addObject("lng", longitude);
        mv.addObject("lat", latitude);

        mv.setViewName("m/driver");
        return mv;
    }


    @RequestMapping(value = "designatedDriver", method = RequestMethod.POST)
    public @ResponseBody
    Result<Order> customerOrder(
        Double longitude, Double latitude, String phone, Long driverId, Integer type,
        String timestamp) {

        logger.debug("recv phone:{},driverId:{},longitude:{},latitude:{},timestamp:{}",
            phone, driverId, longitude, latitude, timestamp);

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);
        try {

            Driver driver = driverService.findOne(driverId);
            Passenger passenger = memberService.findOnePassengerByPhone(phone);
            if (null == passenger) {
                passenger = new Passenger();
                passenger.setType(Passenger.TYPE_PASSENGER);
                passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_WEIXIN);
                passenger.setAllowOverdraw(Boolean.FALSE);

                Company company = companyService.getMain();
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());
                Result<Passenger> result_p = memberService.createPersonal(passenger);

                if (result_p.isSuccess()) {
                    passenger = result_p.getResult();

                    ReactorVo rVo = new ReactorVo();
                    rVo.setPassenger(result_p.getResult());
                    rVo.setActivityEvent(ActivityEvent.newRegister);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);
                }

            }

            Order order = new Order();

            try {
                order.setFromPlace(
                    HttpClientUtil.getPlaceByLngAndLat(longitude, latitude).replaceAll("^.*?市", "")
                        .replaceAll("^.*?省", ""));
            } catch (Exception e) {
                logger.error(e.getMessage());
            }

            order.setClientLongitude(longitude);
            order.setClientLatitude(latitude);
            order.setClientName(passenger.getName());
            order.setClientPhone(phone);
            order.setFromSource("微信下单");
            order.setServerTime(new Date());
            order.setStatus(Order.ORDER_STATUS_NEW);
            order.setOrderCarType(OrderCarType.daijia);
            order.setOrderCarTypeDetail(OrderCarTypeDetail.jhdj);

            orderService.customerOrder(order, driver, passenger, null);

            result.setMessage("下单成功"); //下单成功
            result.setSuccess(true);

        } catch (Exception e) {
            logger.error(e.getMessage());

        }
        return result;
    }


    @RequestMapping(value = "rateData", method = RequestMethod.POST)
    public @ResponseBody
    List<Map<String, Object>> couponData(
        Long driverId,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "limit") Integer limit) {

        Page<Rate> result = null;

        if (null == page) {
            page = 0;
        }
        if (null == limit) {
            limit = 10;
        }
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        result = rateService.pageRateByDriver(driverId, page, limit);
        for (Rate rate : result.getContent()) {

            Map<String, Object> map = new HashMap<String, Object>();
            Date created = rate.getCreated();

            map.put("time", format.format(created));
            String content = rate.getContent();
            if (content.length() > 14) {
                content = rate.getContent().substring(0, 14);
            }
            map.put("content", rate.getContent());
            map.put("starLevel", rate.getStarLevel());
            list.add(map);
        }

        return list;

    }


    @RequestMapping(value = "rentOrder")
    public String rentOrder(Model model) {

        List<Map<String, Object>> citylist = new ArrayList<Map<String, Object>>();
        try {
            citylist = CityList.getCitys();
            model.addAttribute("citylist", citylist);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<Brand> brands = brandService.listWithName();
        List<Map<String, Object>> brandlist = BrandList.getBrands(brands);
        if (!CollectionUtils.isEmpty(brandlist)) {
            model.addAttribute("brandlist", brandlist);
        }

        List<CarType> carTypes = carTypeService.findAll();
        if (!CollectionUtils.isEmpty(carTypes)) {
            List<Map<String, Object>> carTypesMapList = new ArrayList<Map<String, Object>>();
            for (CarType carType : carTypes) {
                Map<String, Object> carTypesMap = new HashMap<String, Object>();
                carTypesMap.put("id", carType.getId());
                carTypesMap.put("name", carType.getName());
                carTypesMapList.add(carTypesMap);
            }
            model.addAttribute("carTypelist", carTypesMapList);
        }

        Calendar calendar = Calendar.getInstance();
        model.addAttribute("week", calendar.get(Calendar.DAY_OF_WEEK) - 1);

        WxSetting setting = settingUtils.getWx();
        model.addAttribute("setting", setting);

        return "m/rentorder";
    }

    @RequestMapping(value = "queryRentalCars", method = RequestMethod.POST)
    public @ResponseBody
    Page<Map<String, Object>> queryRentalCars(
        @RequestParam(required = true, value = "city") String city,
        @RequestParam(required = false, value = "min") BigDecimal min,
        @RequestParam(required = false, value = "max") BigDecimal max,
        @RequestParam(required = false, value = "transmission") Integer transmission,
        @RequestParam(required = false, value = "carTypeIds") Long[] carTypeIds,
        @RequestParam(required = false, value = "brandId") Long brandId,
        @RequestParam(required = false, value = "priceSort") Integer priceSort,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "limit") Integer limit) {

        logger.debug("weixin queryRentalCars city:{}", city);

        Page<Map<String, Object>> result = null;

        if (null == page) {
            page = 0;
        }
        if (null == limit) {
            limit = 10;
        }

        TransmissionCase transmissionStr = null;
        if (null != transmission) {
            if (transmission == 0) {
                transmissionStr = TransmissionCase.AT;
            } else if (transmission == 1) {
                transmissionStr = TransmissionCase.MT;
            }
        }

        if (null != carTypeIds && carTypeIds.length == 0) {
            carTypeIds = null;
        }

        String sequenceStr = "DESC";//降序
        if (priceSort != null && priceSort == 0) {
            sequenceStr = "ASC";
        }

        result = carService
            .findAllWithParam(city, max, min, brandId, carTypeIds, sequenceStr, transmissionStr,
                page, limit);

        return result;

    }


    @RequestMapping(value = "weixinIsLogin")
    public @ResponseBody
    Result<String> phoneSmsInfo(HttpServletRequest req) {
        HttpSession session = req.getSession();
        Object weixin_phone_obj = session.getAttribute("weixin_phone");

        Result<String> result = new Result<String>();
        result.setSuccess(false);

        Map<String, String> map = new HashMap<String, String>();

        if (null != weixin_phone_obj) {
            String weixin_phone = (String) weixin_phone_obj;
            result.setSuccess(true);
            map.put("phone", weixin_phone);
            result.setObject(map);
            return result;
        } else {
            map.put("error", "HASNOTLOGIN");
            result.setObject(map);
            return result;
        }

    }
}
